from .Dtime import get_now_time
from ..utils.createId import create_id
from .connect_mysql import Mysql
from ..utils.desen import MyThread, MyProcess
from .test_conn import TestMysqlConn
from rest_framework.response import Response
from rest_framework import viewsets
from .serializers import QueryDatabaseSerializers, RunSqlTaskSerializers
from connect.models import QueryDatabase, RunSqlTask
from connect.filters import RunSqlTaskFilter



# 查询数据库表字段
class QueryDatabaseInfoViewSet(viewsets.ModelViewSet):
    queryset = QueryDatabase.objects.all()
    serializer_class = QueryDatabaseSerializers

    # 重写创建方法
    def create(self, request, *args, **kwargs):
        query_database_info = {'address': request.data["s_address"], 'types': request.data["s_types"],
                               'passwd': request.data["s_passwd"], 'port': request.data["s_port"],
                               'user': request.data["s_user"]}
        # 判断数据库正常连接
        test_mysql_msg = TestMysqlConn(request.data)

        if test_mysql_msg is None:
            results = {"results": Mysql.main(query_database_info), "code": "200", "msg": "查询成功!"}
        elif test_mysql_msg is not None:
            results = {"code": "400", "msg": test_mysql_msg}
        # 返回查询状态 成功则返回数据库表字段信息
        return Response(results)


# code：200 成功 400 失败（查看DesenData） 401 结果保存失败
class RunSqlTaskViewSet(viewsets.ModelViewSet):
    queryset = RunSqlTask.objects.all()
    serializer_class = RunSqlTaskSerializers
    filter_class = RunSqlTaskFilter

    def create(self, request, save_data_list=None, *args, **kwargs):
        # 接收前端查询信息
        save_data_list = {'s_address': request.data["s_address"], 's_types': request.data["s_types"],
                          's_port': request.data["s_port"], 's_user': request.data["s_user"],
                          'd_address': request.data["d_address"], 'd_types': request.data["d_types"],
                          'd_port': request.data["d_port"], 'd_user': request.data["d_user"]}
        taskid = create_id()
        data = {"database": save_data_list, "t_status": "运行中", "t_taskid": taskid,
                "t_datanumeber": "0", "t_endtime": get_now_time(), "t_dbinfo": ""}
        db_info = request.data
        db_info.update({"task": taskid})
        # 调用查询sql、插入sql脚本
        start_time = get_now_time()
        task = MyThread(kwargs=db_info)
        task.start()
        task.join()
        res = task.task()[0]
        end_time = get_now_time()
        if res["code"] == "200":
            res_up = RunSqlTask.objects.filter(t_taskid=taskid)
            res_up.update(t_dbinfo=res, t_status="已完成", t_endtime=end_time, t_datanumeber=res["count"])
        # 序列化
        t_serializer = RunSqlTaskSerializers(data=data)
        if t_serializer.is_valid():
            t_serializer.save()
            response_data = {"code": "200", "msg": "执行成功！"}
        else:
            msg_err = t_serializer.error_messages
            # code： 401  打印t_serializer.error_messages
            # print(t_serializer.errors)
            response_data = {"code": "201", "msg": msg_err}
        # print(response_data)
        return Response(response_data)

